package zcw.com.lib_leet_code;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import zcw.com.lib_leet_code.bean.TreeNode;
import zcw.com.lib_leet_code.util.Util;

/**
 * Created by 朱城委 on 2021/7/12.<br><br>
 *
 * 翻转二叉树。
 */
public class Topic226 {

    public static void main(String[] args) {
        Topic226 instance = new Topic226();

        List<Integer> list = Arrays.asList(4,2,7,1,3,6,9);
        TreeNode root = Util.createTree(list);
        root = instance.invertTree(root);
        Util.levelTravelTree(root);
        System.out.println();

        list = Arrays.asList(2,1,3);
        root = Util.createTree(list);
        root = instance.invertTree(root);
        Util.levelTravelTree(root);
        System.out.println();

        list = Collections.emptyList();
        root = Util.createTree(list);
        root = instance.invertTree(root);
        Util.levelTravelTree(root);
        System.out.println();
    }

    public TreeNode invertTree(TreeNode root) {
        invert(root);
        return root;
    }

    private void invert(TreeNode root) {
        if(root == null) {
            return;
        }

        TreeNode left = root.left;

        root.left = root.right;
        root.right = left;

        invert(root.left);
        invert(root.right);
    }
}
